﻿using WRJClient.DAL;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using WRJClient.Net;
using WRJClient.Common;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using WRJClient.UI;
using WRJClient.ViewModel;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using Newtonsoft.Json;
using ToastNotifications;
using ToastNotifications.Lifetime;
using ToastNotifications.Messages;
using ToastNotifications.Position;
using System.Threading;
using System.Windows.Threading;

namespace WRJClient.UI.SystemMonitor
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, IDisposable
    {
        private Notifier _notifier;
        class DataBody<T>
        {
            public string Name { get; set; }
        }

        public MainWindow()
        {
            InitializeComponent();
            init();
        }

        private void init()
        {
            if (!string.IsNullOrEmpty(Properties.Settings.Default.WorkStationId))
            {
                otherPanel.Visibility = Visibility.Collapsed;
            }

            ActiveMqConnector.GetInstance().ClientId = "SystemMonitor_" + DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss.fff");
            topoTree.SelectedItemChanged += TopoTree_SelectedItemChanged;
            infoTree.SelectedItemChanged += TopoTree_SelectedItemChanged;
            messageListView.ItemsSource = MessageManager.Instance.Msgs;
            refreshButton.DataContext = UpdateManager.Instance;

            _notifier = new Notifier(cfg =>
            {
                cfg.PositionProvider = new WindowPositionProvider(
                    parentWindow: Application.Current.MainWindow,
                    corner: Corner.TopRight,
                    offsetX: 10,
                    offsetY: 10);

                cfg.LifetimeSupervisor = new TimeAndCountBasedLifetimeSupervisor(
                    notificationLifetime: TimeSpan.FromSeconds(3),
                    maximumNotificationCount: MaximumNotificationCount.FromCount(5));

                cfg.Dispatcher = Application.Current.Dispatcher;
            });
            MessageManager.Instance.ShowMessage += InstanceShowMessage;

            uavHead.DataContext = UAVManager.Instance;
            workStationHead.DataContext = WorkStationManager.Instance;
            missionHead.DataContext = MissionManager.Instance;
        }

        private void InstanceShowMessage(object sender, MessageEventArgs e)
        {
            switch (e.Level)
            {
                case "success":
                    _notifier.ShowSuccess(e.Message);
                    break;
                case "info":
                    _notifier.ShowInformation(e.Message);
                    break;
                case "warning":
                    _notifier.ShowWarning(e.Message);
                    break;
                case "error":
                    _notifier.ShowError(e.Message);
                    break;
                default:
                    break;
            }
        }

        private void showLoginWindow()
        {
            LoginWindow login = new LoginWindow { Owner = this, TitleName = "无人机巡检系统监控" };
            bool? result = login.ShowDialog();
            if (result != true)
            {
                //showLoginWindow();
            }
            loadDataAsync();
        }


        private void TopoTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            body.Children.Clear();
            TopoTreeNodeItem item = e.NewValue as TopoTreeNodeItem;
            if (item != null)
            {
                switch (item.Type)
                {
                    case "ControlCenterViewModel":
                        body.Children.Add(new ControlCenterView(item.ViewModel as ControlCenterViewModel));
                        break;
                    case "WorkStationViewModel":
                        body.Children.Add(new WorkStationView(item.ViewModel as WorkStationViewModel));
                        break;
                    case "UAVViewModel":
                        body.Children.Add(new UavView(item.ViewModel as UAVViewModel));
                        break;
                    case "MissionViewModel":
                        body.Children.Add(new MissionView(item.ViewModel as MissionViewModel));
                        break;
                    case "AirlineViewModel":
                        body.Children.Add(new AirlineView(item.ViewModel as AirlineViewModel));
                        break;
                    case "ZoneViewModel":
                        body.Children.Add(new ZoneView(item.ViewModel as ZoneViewModel));
                        break;
                    case "InfomationViewModel":
                        body.Children.Add(new InfomationView(item.ViewModel as InfomationViewModel));
                        break;
                    default:
                        if (item.DisplayName == "统计分析")
                        {
                            body.Children.Add(new AnalyticView());
                        }
                        break;
                }

            }
        }

        private async void loadDataAsync()
        {
            await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate ()
            {
                reloadData();
            });

        }

        private void reloadData()
        {
            DataLoader.Instance.LoadControlCenter();
            Thread.Sleep(100);
            DataLoader.Instance.LoadUAV();
            Thread.Sleep(100);
            DataLoader.Instance.LoadWorkStation();
            Thread.Sleep(100);
            DataLoader.Instance.LoadMission();
            Thread.Sleep(100);
            DataLoader.Instance.LoadInfomation();
            Thread.Sleep(100);
            DataLoader.Instance.LoadAirline();
            Thread.Sleep(100);
            DataLoader.Instance.LoadZone();

            UpdateManager.Instance.Reset();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(Api.Token))
            {
                showLoginWindow();
                ActiveMqConnector.GetInstance().Connect();
            }
        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (WindowState == WindowState.Maximized)
            {
                WindowStyle = WindowStyle.None;
            }
            else
            {
                WindowStyle = WindowStyle.SingleBorderWindow;
            }
        }


        private void MainWindow_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Point point = e.GetPosition(this);
            if (messageListView.Visibility != Visibility.Visible)
            {
                if (point.Y <= 2)
                {
                    messageListView.Visibility = Visibility.Visible;
                }
            }
            else
            {
                HitTestResult result = VisualTreeHelper.HitTest(messageListView, point);
                if (result == null)
                {
                    messageListView.Visibility = Visibility.Hidden;
                }
            }
        }

        private void Button_OnClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button != null)
            {
                if (button.Name.CompareTo("refreshButton") == 0)
                {
                    if (string.IsNullOrEmpty(Api.Token))
                    {
                        showLoginWindow();
                    }
                    loadDataAsync();
                }
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        #region IDisposable Support
        private bool disposedValue = false; // 要检测冗余调用

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)。
                }

                // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
                _notifier.Dispose();

                // TODO: 将大型字段设置为 null。

                disposedValue = true;
            }
        }

        // TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
        // ~MainWindow() {
        //   // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
        //   Dispose(false);
        // }

        // 添加此代码以正确实现可处置模式。
        public void Dispose()
        {
            // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
            Dispose(true);
            // TODO: 如果在以上内容中替代了终结器，则取消注释以下行。
            // GC.SuppressFinalize(this);
        }
        #endregion

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;
            if (menuItem != null)
            {
                if (menuItem.Name.CompareTo("clearMsgMenuItem") == 0)
                {
                    MessageManager.Instance.Msgs.Clear();
                }
            }

        }
    }
}
